<?php
namespace app\models;

use app\models\UserLevel;

class UserCredit extends IModel {
    public $table = 't_user_credit';

    public function getUserLevel($uid) {
        $data = $this->getOneByCondition('experience', 'uid=' . $uid);
        $ret = ['experience' => 0];

        if($data) {
            $ret['experience'] = $data['experience'];
        }

        $level = (new UserLevel())->getLevelInfoByExp($ret['experience']);

        return array_merge($ret, $level);
    }

    public function addExp($uid, $exp) {
        global $_G;
        $total = $this->count('uid=' . $uid, 'uid');

        // 不存在就插入一条
        if($total < 1) {
            $newData = ['uid' => $uid, 'experience' => $exp];
            $this->insert($newData);
            return;
        }

        $sql = 'UPDATE ' . $this->table . ' set experience=experience + ? where uid=?';

        $this->db->prepareStatement($sql)->bindValues([$exp, $uid])->execute();
    }

    public function addScore($uid, $score) {
        $total = $this->count('uid=' . $uid, 'uid');

        // 不存在就插入一条
        if($total < 1) {
            $newData = ['uid' => $uid, 'score' => $score];
            $this->insert($newData);
            return;
        }

        $sql = 'UPDATE ' . $this->table . ' set score=score + ? where uid=?';

        $this->db->prepareStatement($sql)->bindValues([$score, $uid])->execute();
    }
}
